package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserDao userDao;

    @Override
    public List<Menu> findAll() {
        return menuDao.findAll();
    }

    public List<Menu> getMenuTree(String name) {

        //获取用户名
        User user = userDao.findByUsername(name);

        List<Role> roleList = roleDao.getRoleList(user.getId());

        //获取用户，根据用户获取用户所拥有的菜单
        List<Menu> menus = new ArrayList<>();

        if(roleList != null) {
            for (Role role : roleList) {
                menus.addAll(menuDao.findMenusByRoleId(role.getId()));
            }
        }

        if(menus == null) {
            return null;
        }

        //获取所有的角色
        List<Menu> menuList = menuDao.findAll();

        List<Menu> list = new ArrayList<>();

        //获取用户所拥有的菜单
        getMenu(menuList,menus,list);


        return list;
    }

    private void getMenu(List<Menu> menuList,List<Menu> menus,List<Menu> list) {
        //判断是否拥有该角色
        if(menuList != null && menuList.size() >0 ) {
            for (Menu menu : menuList) {
                //获取角色的id
                Menu userMenu = getUserMenu(menu, menus);
                List<Menu> childrenMenuList = new ArrayList<>();
                if(menu.getChildren() != null) {
                    for (Menu child : menu.getChildren()) {
                        Menu childrenMenu = getUserMenu(child, menus);
                        if(childrenMenu != null ) {
                            childrenMenuList.add(childrenMenu);
                        }
                    }
                }

                if(userMenu != null) {
                    userMenu.setChildren(childrenMenuList);
                    list.add(userMenu);
                }
            }
        }
    }

    private Menu getUserMenu(Menu menu,List<Menu> menus) {
        Integer menuId = menu.getId();
        for (Menu userMenu : menus) {
            //获取用户角色的id
            Integer userMenuId = userMenu.getId();

            if(menuId == userMenuId) {
                return menu;
            }
        }
        return null;
    }
}
